package com.lydms.web;

import com.lydms.common.ApiResult;
import com.lydms.service.TranslateService;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import net.minidev.json.JSONObject;
import java.util.Map;

/**
 * 翻译服务
 * @author
 */
@RestController
@RequestMapping("/translate")
public class TranslateController {
    private static final Logger logger = LogManager.getLogger(TranslateController.class);

    @Autowired
    private TranslateService translateService;

    //翻译为中文
    private String transToZh = "zh";
    //翻译为英文
    private String transToEn = "en";


    /**
     * 英语翻译
     * @param en
     * @return
     */
    @RequestMapping(value = "/english", method = {RequestMethod.POST})
    public ApiResult translateEnglish(@RequestBody Map<String,Object> en) {
        logger.info("入参为:English: {}",en.get("english"));
        JSONObject json = new JSONObject();
//        1、入参的校验
        String english = null;
        if (en.get("english") != null) {
            english = (String) en.get("english");
        }
        if (StringUtils.isBlank((String)en.get("english"))) {
            return ApiResult.fail(105, "请传入英语单词");
        }

//        2、查询单个数据
        String chinese = translateService.translate(english,transToZh);
//        3、返回值判断
        if (chinese == null) {
            return ApiResult.fail(103, "调用翻译失败");
        }
        json.put("english",english);
        json.put("chinese",chinese );
        return ApiResult.succ(json);

    }

    /**
     * 中文翻译
     * @param en
     * @return
     */
    @RequestMapping(value = "/chinese", method = {RequestMethod.POST})
    public ApiResult translateChinese(@RequestBody Map<String,Object> en) {
        logger.info("入参为:Chinese: {}",en.get("chinese"));
        JSONObject json = new JSONObject();
//        1、入参的校验
        String chinese = null;
        if (en.get("chinese") != null) {
            chinese = (String) en.get("chinese");
        }
        if (StringUtils.isBlank((String)en.get("chinese"))) {
            return ApiResult.fail(105, "请传入中文");
        }

//        2、查询单个数据
        String english = translateService.translate(chinese,transToEn);
//        3、返回值判断
        if (english == null) {
            return ApiResult.fail(103, "调用翻译失败");
        }
        json.put("chinese",chinese);
        json.put("english",english );
        return ApiResult.succ(json);

    }


}


